package com.sample.navigation.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Point;
import android.graphics.PointF;
import android.graphics.RectF;
import android.graphics.Shader;
import android.util.AttributeSet;
import android.view.View;

import com.sample.navigation.R;

import androidx.annotation.Nullable;

public class IndicatorView extends View {
    private RectF rect;
    private Paint paint;
    private Path path;
    private int index;
    private int select;
    private PointF datumPoint;
    private int backgroundColor_start;
    private int backgroundColor_end;
    public IndicatorView(Context context) {
        this(context, null);
    }

    public IndicatorView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public IndicatorView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.IndicatorView);
        backgroundColor_start = ta.getColor(R.styleable.IndicatorView_indicator_background_start, Color.TRANSPARENT);
        backgroundColor_end = ta.getColor(R.styleable.IndicatorView_indicator_background_end, Color.TRANSPARENT);
        ta.recycle();

        datumPoint = new PointF();
        rect = new RectF();
        paint = new Paint();
        paint.setAntiAlias(true);
    }

    public void setSplitIndex(int index){
        this.index = index;
    }

    public void setSelect(int select){
        if(select < this.index){
            this.select = select;
        }
        invalidate();
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        rect.left = getPaddingLeft();
        rect.top = getPaddingTop();
        rect.right = w - getPaddingRight();
        rect.bottom = h - getPaddingBottom();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        path = new Path();
        path.addRect(rect, Path.Direction.CCW);

        datumPoint.x =  (2 * select + 1)* rect.width() / 8;
        datumPoint.y = getPaddingTop();

        int offset = getPaddingTop();

        path.moveTo(datumPoint.x + offset, datumPoint.y);
        path.lineTo(datumPoint.x, datumPoint.y - offset);
        path.lineTo(datumPoint.x - offset, datumPoint.y);
        path.close();

        LinearGradient linearGradient = new LinearGradient(
                rect.left, rect.top,
                rect.right,rect.bottom,
                backgroundColor_start,
                backgroundColor_end,
                Shader.TileMode.CLAMP);
        paint.setShader(linearGradient);
        canvas.drawPath(path, paint);
    }
}
